import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {View, Image, Text} from '@tarojs/components';
import {AtIcon, AtInput} from 'taro-ui'
import {GetRequest} from "../../utils/tools";
import {http} from "../../utils/http";
import {TARO_ENV, RESOURCE_URL, APP_SCENIC_ALL} from "../../constants/api";
import typeList from './typeList';
import "./index.scss";
// 默认景点
const defaultIcon = "https://resource.ivcheng.com/upload/images/20220831/1661930803615_272.png";

export default class InnerNavigate extends Component {
	constructor(props) {
		super(props);
		this.state = {
			start: "",
			end: "",
			listDataOri: [],
			listData: [],
			chooseItem: null,
			currentStart: {},
			currentEnd: {}
		};
	}

	componentDidMount() {
		this.getAllScenic();
	}

	// get all scenic
	getAllScenic = async () => {
		const params = Taro.getCurrentInstance().router.params;
		const {
			scenicId: scenic_id,
			pkey,
			id,
			name,
			lat,
			lng,
			address
		} = params;
		const nameStr = name.indexOf("%") > -1 ? decodeURIComponent(name) : name; // 刷新页面时解码name值

		Taro.showLoading({title: "加载中", mask: true});
		const res = await http.HGet(APP_SCENIC_ALL, {scenic_id, "p-key": pkey});
        let datas = res.data || [];
		// 更新图标
		for(let i = 0, len = datas.length; i < len; i++) {
			const type = datas[i].type || "";

			if(!type) datas[i].icon = defaultIcon;
			else {
				for(let t = 0, len2 = typeList.length; t < len2; t++) {
					if(typeList[t].name === type) {
						datas[i].icon = typeList[t].icon;
						break;
					}
				}
			}
		}
		// 匹配参数项
		let chooseItem = null, end = "", currentEnd = {};
		if(!address) {
			chooseItem = datas.find(item => item.id === id || item.name === nameStr);
		}else {
			// 自动选为终点
			if(address === "end") {
				const tempItem = datas.find(item => item.id === id || item.name === nameStr);
				end = tempItem.name;
				currentEnd = Object.assign({}, tempItem);
			}
		}
		this.setState({ listData: datas, listDataOri: datas, chooseItem, end, currentEnd }, () => {
			Taro.hideLoading();
		});
	}
	// start
	handleStartInput(value) {
		const { listDataOri } = this.state;
		const listData = listDataOri.filter(item => item.name.indexOf(value) > -1);
		this.setState({ start: value, listData });
	}
	// end
	handleEndInput(value) {
		const { listDataOri } = this.state;
		const listData = listDataOri.filter(item => item.name.indexOf(value) > -1);
		this.setState({ end: value, listData });
	}
	// clear
	clearIpt(keyName) {
		const { listDataOri } = this.state;
		this.setState({ [keyName]: "", listData: [...listDataOri], chooseItem: null });
	}
	// click item
	handleClickName(item) {
		this.setState({ chooseItem: item });
	}
	// choose start
	chooseAsStart(item) {
		const { listDataOri } = this.state;
		this.setState({ start: item.name, currentStart: item, chooseItem: null, listData: listDataOri });
	}
	// choose end
	chooseAsEnd(item) {
		const { listDataOri } = this.state;
		this.setState({ end: item.name, currentEnd: item, chooseItem: null, listData: listDataOri });
	}
	// sure
	doNavigate = () => {
		const { currentStart, currentEnd } = this.state;
		if(!currentStart.name) {
			Taro.showToast({
				title: "请确定起点",
				icon: "none"
			})
			return;
		}
		if(!currentEnd.name) {
			Taro.showToast({
				title: "请确定终点",
				icon: "none"
			})
			return;
		}

		const mapUri = "https://apis.map.qq.com/uri/v1/routeplan?type=walk&";
		const from = `from=${currentStart.name}&`;
        const fromcoord = `fromcoord=${currentStart.latitude},${currentStart.longitude}&`;
        const to = `to=${currentEnd.name}&`;
        const tocoord = `tocoord=${currentEnd.latitude},${currentEnd.longitude}`;
        const uriOther = "&policy=2&referer=NUMBZ-QW4RF-CLQJI-J5A77-XIRM3-26BWY";
        const requestURI = `${mapUri}${from}${fromcoord}${to}${tocoord}${uriOther}`;

        window.open(requestURI, "_blank");
	}

	render() {
		const { start, end, listData, chooseItem, currentStart, currentEnd } = this.state;

		return (
			<View className="inner-navigate-page">
				<View className="search-area">
					<View className="sa-item">
						<View className="sai-label">起点</View>
						<View className="sai-ipt">
							<AtInput
								name='start'
								type='text'
								placeholder='请输入或选择起点'
								value={start}
								className="sai-name"
								onChange={this.handleStartInput.bind(this)}
							/>
							{
								start &&
								<AtIcon
									value='close-circle'
									size='22'
									color='#A0A5A4'
									onClick={() => this.clearIpt("start")}
								/>
							}
						</View>
					</View>
					<View className="sa-item">
						<View className="sai-label">终点</View>
						<View className="sai-ipt">
							<AtInput
								name='end'
								type='text'
								placeholder='请输入或选择终点'
								value={end}
								className="sai-name"
								onChange={this.handleEndInput.bind(this)}
							/>
							{
								end &&
								<AtIcon
									value='close-circle'
									size='22'
									color='#A0A5A4'
									onClick={() => this.clearIpt("end")}
								/>
							}
						</View>
					</View>
					<View className="sa-btn" onClick={this.doNavigate}>确定</View>
				</View>

				<View className="list-area">
					{
						listData.map((item, index) => (
							<View className="la-item" key={index}>
								<View className="left-img">
									<Image src={item.icon} mode='aspectFit' className="lai-img" />
								</View>
								<View className="right-scenic">
									<View className="title" onClick={() => this.handleClickName(item)}>{item.name}</View>
									{
										chooseItem && chooseItem.id === item.id &&
										<View
											className="btn-cmn start-btn"
											onClick={() => this.chooseAsStart(item)}
										>选为起点</View>
									}
									{
										chooseItem && chooseItem.id === item.id &&
										<View
											className="btn-cmn end-btn"
											onClick={() => this.chooseAsEnd(item)}
										>选为终点</View>
									}
								</View>
							</View>
						))
					}
				</View>
			</View>
		)
	}
}
